<script setup lang="ts">
import { ImageViewer } from "@/components/common/ImageViewer";
import { dealDataAdd, dealDataExcept, dealDataRide } from "@/utils/common";
import { clearNoNum, clearSuffix } from "@/utils/inupt";
import { cloneDeep } from "@pureadmin/utils";
import { onMounted, reactive, ref, watch } from "vue";
import { formRules } from "../utils/rule";
import { FormProps } from "../utils/types";
import { useShipperAdd } from "./columns";

import Delete from "@iconify-icons/ep/delete";
// 获取商品列表
import { getGoodsList } from "@/api/basicArchives/goods";
import {
  purchaseDetail,
  purchaseOrderCalc
} from "@/api/orderManag/shipperPrepar";

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    id: "",
    supplierId: undefined,
    depositoryId: undefined,
    addItemList: undefined,
    updateItemList: undefined,
    deleteOrderItemIds: undefined,
    fareType: 1, // 运费类型 1包邮 2提前支付 3到付
    fare: undefined,
    orderNum: undefined,
    orderPrice: undefined,
    des: "",
    dataList: []
  }),
  supplierList: null,
  depositoryList: null
});

const ruleFormRef = ref();
const loadingDetail = ref(false);
const newFormInline = ref(props.formInline);

//  左边供应商商品列表
let goodsList = ref([]);
goodsList.value = [
  // {
  //   id: 1,
  //   logo: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
  //   spmc: "商品名称商品名称1",
  //   ggList: [
  //     { id: 1, name: "蓝" },
  //     { id: 2, name: "红" },
  //     { id: 3, name: "黄" }
  //   ],
  //   checkTagsID: [],
  //   price: 28,
  //   spdj: undefined,
  //   spsl: undefined,
  //   xj: "",
  //   fthdj: "",
  //   fthzj: ""
  // }
];

let checkGoodsID = reactive([]);
function chooseGood(item) {
  // 左边商品选中或取消
  const index = checkGoodsID.indexOf(item.id);
  if (index != -1) {
    // 移除
    checkGoodsID.splice(index, 1);
    let findIndex = newFormInline.value.dataList.findIndex(
      v => v.goodsId == item.id
    );
    if (findIndex != -1) {
      newFormInline.value.dataList.splice(findIndex, 1);
    }
  } else {
    // 新增
    checkGoodsID.push(item.id);
    if (item.goodsSpecList.length == 0 || item.goodsSpecList.length == 1) {
      // 如果没有商品规格，则直接添加数据
      item.spgg = "--";
      item.spdj = dealDataExcept(item.goodsSpecList[0]?.buyPrice);
      item.spsl = item.orderMin;
      item.xj = undefined;
      item.ftje = undefined;
      item.fthdj = undefined;
      item.fthzj = undefined;
      item.specImageJson = item.specImageJson || item.imageJson;
      item.specCode = item.goodsSpecList[0]?.specCode;
      item.specName = item.goodsSpecList[0]?.specName;
      item.barCode = item.goodsSpecList[0]?.barCode;
      item.goodsId = item.id;
      let row = item;
      newFormInline.value.dataList.push(row);
    }
  }
}

function checkTags(item, tag) {
  // 多规格商品根据规格添加数据，有多个规格可以添加多个数据
  // 左边商品规格选中或取消
  const index = item.checkTagsID.indexOf(tag.specName);
  if (index == -1) {
    item.checkTagsID.push(tag.specName);
    item.spgg = tag.specName;
    item.spdj = dealDataExcept(tag.buyPrice);
    item.spsl = item.orderMin;
    item.specCode = tag.specCode;
    item.specImageJson = tag.specImageJson || item.imageJson;
    item.specName = tag.specName;
    item.barCode = tag.barCode;
    item.goodsId = item.id;
    let row = cloneDeep(item);
    newFormInline.value.dataList.push(row);
  } else {
    item.checkTagsID.splice(index, 1);
    newFormInline.value.dataList.splice(index, 1);
  }
}

function getRef() {
  return ruleFormRef.value;
}

const searchValue = ref("");
const dataLoading = ref(false);

const pagination = reactive({ current: 1, pageSize: 18, total: 0 });
const onPageSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.current = 1;
  loadGoodsList();
};
const onCurrentChange = (current: number) => {
  pagination.current = current;
  loadGoodsList();
};

const { columns } = useShipperAdd();

// 右边删除按钮
function onDel(row) {
  // 编辑删除 deleteOrderItemIds  订单删除的商品id数组
  if (row.type == "edit") {
    // 编辑删除 商品id数组
    newFormInline.value.deleteOrderItemIds.push(row.id);
  }
  console.log(newFormInline.value.deleteOrderItemIds);

  if (row.spgg == "--") {
    // 没有商品规格的删除

    const index = checkGoodsID.indexOf(row.id);
    checkGoodsID.splice(index, 1);

    const i = newFormInline.value.dataList.indexOf(row);
    newFormInline.value.dataList.splice(i, 1);
  } else {
    // 多规格商品的删除

    row.goodsSpecList?.forEach(v => {
      if (row.spgg == v.specName) {
        const index = newFormInline.value.dataList.indexOf(row);
        newFormInline.value.dataList.splice(index, 1);

        // 根据右边数据的商品规格，取消左边多规格的选中状态
        goodsList.value.forEach((item, i) => {
          if (item.id == row.id) {
            const index = goodsList.value[i].checkTagsID.indexOf(row.spgg);
            goodsList.value[i].checkTagsID.splice(index, 1);
          }
        });
      }
    });
  }
}

watch(
  () => newFormInline.value.dataList,
  val => {
    // 计算分摊后单价 分摊后总价
    calcGoodsPrice();
    // let fareType = newFormInline.value.fareType;
    // val?.forEach(item => {
    //   if (item.spdj >= 0 && item.spdj && item.spsl >= 0 && item.spsl) {
    //     item.xj = dealDataRide(item.spdj, item.spsl);
    //     /**
    //      * 如果已经填过运费金额，再次修改商品单价 或者 商品数量
    //      * 重新计算分摊后单价，分摊后总价
    //      */
    //     if (
    //       fareType == 2 &&
    //       newFormInline.value.fare &&
    //       newFormInline.value.fare > 0
    //     ) {
    //       item.ftje = dealDataRide(
    //         dealDataExcept(item.xj, totalPrice.value, 2),
    //         newFormInline.value.fare,
    //         2
    //       );
    //       item.fthdj = dealDataAdd(
    //         dealDataExcept(item.ftje, item.spsl, 2),
    //         item.spdj
    //       );
    //       item.fthzj = dealDataRide(item.fthdj, item.spsl);
    //     } else {
    //       item.ftje = undefined;
    //       item.fthdj = undefined;
    //       item.fthzj = undefined;
    //     }
    //   }
    // });
  },
  { deep: true }
);

/**
 * A商品分摊金额 = A商品总价 / 备货订单总金额 * 备货运费，
 * A商品分摊后单价 = A商品分摊金额 / A商品备货数量 + A商品备货单价
 */
watch(
  () => newFormInline.value.fare,
  val => {
    calcGoodsPrice();
    // if (newFormInline.value.dataList.length > 0) {
    //   let fareType = newFormInline.value.fareType;
    //   newFormInline.value.dataList.forEach(item => {
    //     // 如果分摊金额为0 则分摊单价和分摊金额都为空
    //     if (fareType != 2 || val == 0) {
    //       item.ftje = undefined;
    //       item.fthdj = undefined;
    //       item.fthzj = undefined;
    //       return;
    //     }

    //     // 如果商品小计为空 则跳过
    //     if (!item.xj) return;
    //     // 计算分摊后单价 分摊后总价
    //     item.ftje = dealDataRide(
    //       dealDataExcept(item.xj, totalPrice.value, 2),
    //       newFormInline.value.fare,
    //       2
    //     );
    //     item.fthdj = dealDataAdd(
    //       dealDataExcept(item.ftje, item.spsl, 2),
    //       item.spdj
    //     );
    //     item.fthzj = dealDataRide(item.fthdj, item.spsl);
    //   });
    // }

    // 计算订单总价
    // newFormInline.value.orderPrice = dealDataAdd(totalPrice.value, val);
  },
  { deep: true }
);

// 调用后端接口计算商品价格
const isCalcing = ref(false);
const calcGoodsPrice = async () => {
  if (isCalcing.value) {
    return;
  }
  isCalcing.value = true;
  console.log("calcGoodsPrice-----");

  let dataList = newFormInline.value.dataList;

  // 判断是否需要查询
  let calcGoodList = [];
  if (newFormInline.value.fareType == 2 && newFormInline.value.fare) {
    // 获取有数量需要查询的商品
    let filterList = dataList.map(v => {
      return {
        specCode: v.specCode,
        amount: v.spsl || 1,
        buyPrice: dealDataRide(v.spdj) || 0
      };
    });
    let params = {
      fare: dealDataRide(newFormInline.value.fare),
      fareType: 2,
      addItemList: filterList
    };
    let { data } = await purchaseOrderCalc(params);
    calcGoodList = data.addItemList || [];
  }

  let sumPrice = 0;
  dataList.forEach(v => {
    if (newFormInline.value.fareType == 2 && newFormInline.value.fare) {
      // 后端计算
      let findObj = calcGoodList.find(j => j.specCode == v.specCode);
      if (findObj && findObj.specCode) {
        v.xj = dealDataExcept(findObj.orderItemPrice);
        v.ftje = dealDataExcept(findObj.avgPrice);
        v.fthdj = dealDataExcept(findObj.avgBuyPrice);
        v.fthzj = dealDataExcept(findObj.avgOrderItemPrice);
        sumPrice = dealDataAdd(v.xj, sumPrice);
      }
    } else {
      // 页面计算
      v.xj = dealDataRide(v.spdj, v.spsl);
      v.ftje = undefined;
      v.fthdj = undefined;
      v.fthzj = undefined;
      sumPrice = dealDataAdd(v.xj, sumPrice);
    }
  });

  // 订单合计
  newFormInline.value.orderPrice = dealDataAdd(
    sumPrice,
    newFormInline.value.fare || 0
  );
  setTimeout(() => {
    isCalcing.value = false;
  }, 0);
};

// const totalPrice = computed(() => {
//   let money = newFormInline.value.dataList.reduce((prev, current) => {
//     let cur = isNaN(current.xj) ? 0 : current.xj;
//     return dealDataAdd(cur, prev);
//   }, 0);
//   return money;
// });

function changeRadio(val) {
  if (val != 2) {
    newFormInline.value.fare = undefined;
  }
}

// 供应商
const supplierChange = () => {
  pagination.current = 1;
  pagination.pageSize = 18;
  pagination.total = 0;
  checkGoodsID = [];
  newFormInline.value.dataList = [];
  loadGoodsList();
};

// 选择供应商获取对应的商品列表
async function loadGoodsList() {
  if (!newFormInline.value.supplierId) {
    goodsList.value = [];
    return;
  }

  dataLoading.value = true;
  const params: any = {
    supplierId: newFormInline.value.supplierId,
    filter: 1,
    goodsStatus: 1,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  };
  if (searchValue.value) {
    params.search = searchValue.value;
  }
  const { data } = await getGoodsList(params);
  data.records.forEach(item => {
    item.type = "add";
    item.checkTagsID = [];
  });
  goodsList.value = data.records || [];
  pagination.total = data.total;
  pagination.pageSize = data.pageSize;
  pagination.current = data.pageNum;
  dataLoading.value = false;
}

// 获取详情
async function loadGoodsDetail(id) {
  loadingDetail.value = true;
  let { data } = await purchaseDetail(id);
  let newDatas = data.itemList;
  // 处理返回的值显示  商品名称 商品规格  商品单价 商品数量 小计 分摊金额 分摊后单价 分摊后总价
  newDatas.forEach(item => {
    item.type = "edit";

    // 如果有规格图片 则显示规格图片
    if (item.specImageJson) {
      item.imageJson = item.specImageJson;
    }

    // 如果没有规格名称表示是单规格 则显示--
    if (item.specName) {
      item.spgg = item.specName;
    } else {
      item.spgg = "--";
    }

    // 商品单价
    item.spdj = dealDataExcept(item.buyPrice);

    // 商品数量
    item.spsl = item.amount;

    item.goodsSpecList = newDatas;
  });
  console.log("log", newDatas);
  newFormInline.value.dataList = newDatas;

  // 运费金额
  let fare = undefined;
  if (data.fare && data.fareType == 2) {
    fare = dealDataExcept(data.fare);
  }
  newFormInline.value.fare = fare;
  // newFormInline.value.orderPrice = dealDataExcept(data.orderPrice);
  loadingDetail.value = false;
}

onMounted(async () => {
  if (newFormInline.value.id) {
    loadGoodsDetail(newFormInline.value.id);
    loadGoodsList();
  }
});

defineExpose({ getRef });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :rules="formRules"
    :model="newFormInline"
    label-width="80px"
  >
    <div class="flex">
      <el-form-item label="供应商" prop="supplierId">
        <el-select
          v-model="newFormInline.supplierId"
          filterable
          placeholder="请选择"
          clearable
          class="!w-[300px]"
          :disabled="newFormInline.id ? true : false"
          @change="supplierChange"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.id"
            :label="item.supplierName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="到货仓库" prop="depositoryId" class="ml-5">
        <el-select
          v-model="newFormInline.depositoryId"
          filterable
          placeholder="请选择"
          clearable
          :disabled="newFormInline.id ? true : false"
          class="!w-[280px]"
        >
          <el-option
            v-for="item in depositoryList"
            :key="item.id"
            :label="item.depositoryName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </div>
    <!-- 商品列表 -->
    <div class="goods-box">
      <div class="g-left">
        <div class="search">
          <el-input
            v-model="searchValue"
            class="!w-[300px]"
            placeholder="输入商品编码/名称后回车选中"
            clearable
            @change="loadGoodsList"
          >
            <template #suffix>
              <el-icon class="el-input__icon">
                <IconifyIconOffline
                  v-show="searchValue.length === 0"
                  icon="ri:search-line"
                />
              </el-icon>
            </template>
          </el-input>
        </div>
        <div v-loading="dataLoading" class="content">
          <ul v-if="goodsList.length > 0" class="goods-items">
            <div v-for="(item, i) in goodsList" :key="i" class="goods-pitem">
              <li
                :class="
                  ((item.goodsSpecList?.length == 0 ||
                    item.goodsSpecList?.length == 1) &&
                    checkGoodsID.includes(item.id)) ||
                  (item.goodsSpecList?.length > 1 &&
                    item.checkTagsID.length > 0)
                    ? 'active'
                    : ''
                "
                class="goods-item"
                @click="chooseGood(item)"
              >
                <ImageViewer
                  :src="item.imageJson"
                  radius="8px"
                  width="57px"
                  height="57px"
                  class="mr-2"
                />
                <div class="item-rig">
                  <div class="top">
                    <div class="name truncate">
                      <el-tooltip
                        :content="item.goodsName"
                        placement="top-start"
                      >
                        {{ item.goodsName }}
                      </el-tooltip>
                    </div>
                    <div
                      v-if="item.goodsSpecList && item.goodsSpecList.length > 0"
                      class="price"
                    >
                      ￥<span>{{
                        dealDataExcept(item.goodsSpecList[0]?.buyPrice)
                      }}</span>
                    </div>
                  </div>
                  <div v-if="item.goodsSpecList?.length > 1" class="spec-boxs">
                    <span
                      v-for="(tag, j) in item.goodsSpecList"
                      :key="j"
                      :class="
                        item.checkTagsID.includes(tag.specName) ? 'active' : ''
                      "
                      class="spec-item"
                      @click.stop="checkTags(item, tag)"
                    >
                      <el-tooltip placement="top-start">
                        <template #content>
                          <div>
                            {{ tag.specName }}
                            (￥{{ dealDataExcept(tag.buyPrice) }} )
                          </div>
                        </template>
                        <span class="truncate block">
                          {{ tag.specName }}
                        </span>
                      </el-tooltip>
                    </span>
                  </div>
                </div>
              </li>
            </div>
          </ul>
          <el-empty v-else description="暂无数据" />
        </div>
        <div class="footer">
          <el-pagination
            v-model:currentPage="pagination.current"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[18, 36, 48]"
            :background="true"
            layout="total,sizes, prev, pager, next, jumper"
            @size-change="onPageSizeChange"
            @current-change="onCurrentChange"
          />
        </div>
      </div>
      <div class="g-right">
        <h3 class="text-[#29281C] p-3">商品选择</h3>
        <pure-table
          class="!w-full"
          align-whole="center"
          row-key="id"
          :data="newFormInline.dataList"
          :columns="columns"
          height="calc(100vh - 555px)"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
        >
          <template #operation="{ row }">
            <div class="flex justify-center">
              <iconifyIconOffline
                class="text-red-500 text-lg cursor-pointer"
                :icon="Delete"
                @click="onDel(row)"
              />
            </div>
          </template>
        </pure-table>
        <div class="fare-form">
          <el-form-item label="运费" prop="depositoryIdList">
            <el-radio-group
              v-model="newFormInline.fareType"
              @change="changeRadio"
            >
              <el-radio :value="1">包邮</el-radio>
              <el-radio :value="2">提前支付</el-radio>
              <el-radio :value="3">到付</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="newFormInline.fareType == 2"
            label="运费金额"
            prop="fare"
          >
            <el-input
              v-model="newFormInline.fare"
              placeholder="请输入"
              clearable
              class="!w-[238px]"
              @input="newFormInline.fare = clearNoNum($event)"
              @blur="
                newFormInline.fare = Number(
                  clearSuffix(newFormInline.fare + '')
                )
              "
            />
          </el-form-item>
          <el-form-item label="备注" prop="des">
            <el-input
              v-model="newFormInline.des"
              clearable
              :rows="4"
              class="!w-[238px]"
              placeholder="请输入"
              type="textarea"
            />
          </el-form-item>
        </div>

        <div class="goods-total">
          <div class="lef flex items-center text-sm text-[#29281C]">
            共
            <span class="text-[#F76847] mx-0.5">
              {{ newFormInline.dataList.length }}
            </span>
            件商品
          </div>
          <div class="text-lg text-[#F76847] min-w-[110px]">
            合计：
            <span v-if="newFormInline.dataList.length > 0"
              >¥ {{ newFormInline.orderPrice || "--" }}</span
            >
            <span v-else>--</span>
          </div>
        </div>
      </div>
    </div>
  </el-form>
</template>
<style lang="scss" scoped>
.goods-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  height: calc(100vh - 235px);
  .g-left,
  .g-right {
    position: relative;
    border-radius: 12px;
    border: 1px solid #e5e5da;
    overflow: hidden;
  }
  .g-left {
    width: 60%;
    display: flex;
    flex-direction: column;
    margin-right: 12px;
    .search {
      padding: 12px 12px;
      border-bottom: 1px solid #efefef;
    }
  }
  .g-right {
    min-width: 615px;
    width: 40%;
    display: flex;
    flex-direction: column;
    .fare-form {
      flex: 1;
      padding-top: 10px;
    }
    .goods-total {
      width: 100%;
      padding: 5px 16px;
      border-top: 1px solid #f2f2eb;
      display: flex;
      justify-content: space-between;
    }
  }
  .content {
    flex: 1;
    padding: 6px;
    overflow: auto;
  }
  .goods-items {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    box-sizing: border-box;
    .goods-pitem {
      width: 33.333%;
    }
    .goods-item {
      padding: 6px;
      margin: 6px;
      background: #ffffff;
      box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.12);
      border-radius: 8px 8px 8px 8px;
      border: 2px solid transparent;
      min-height: 75px;
      display: flex;
      justify-content: space-between;
      cursor: pointer;
      box-sizing: border-box;
      .item-rig {
        flex: 1;
        overflow: hidden;
        position: relative;
        .top {
          display: flex;
          margin-bottom: 5px;
          .name {
            flex: 1;
            font-size: 14px;
            font-weight: bold;
            color: #29281c;
          }
        }
        .price {
          font-weight: normal;
          font-size: 14px;
          color: #f76847;
          span {
            font-size: 15px;
            font-weight: bold;
          }
        }
        .spec-boxs {
          display: flex;
          flex-wrap: wrap;
          gap: 5px;
          .spec-item {
            font-size: 12px;
            padding: 3px 5px;
            color: #6296ff;
            max-width: 70px;
            border: 1px solid #6296ff;
            border-radius: 5px;
            &.active {
              color: #fff;
              background: #6296ff;
            }
          }
        }
      }
      &.active {
        border: 2px solid #6296ff;
      }
    }
    .goods-item:hover {
      border: 2px solid #6296ff;
    }
  }
  .footer {
    padding: 12px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #efefef;
  }
}

.truncates {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

@media (max-width: 1350px) {
  .goods-box .goods-items .goods-pitem {
    width: 50%;
  }
}
</style>
